package com.zhuge_new.Activity;

import android.arch.lifecycle.ViewModelProvider;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.maning.mndialoglibrary.MToast;
import com.zhuge_new.Base.BaseActivity;
import com.zhuge_new.Dialog.PatmentDialog;
import com.zhuge_new.R;
import com.zhuge_new.bean.RateBean;
import com.zhuge_new.http.StringDialogCallback;
import com.zhuge_new.share.BaseHttp;
import com.zhuge_new.untils.ActivityStack;
import com.zhuge_new.untils.DataParse;
import com.zhuge_new.untils.PreferencesUtils;
import com.zhuge_new.untils.Tailuntils;

import org.json.JSONException;
import org.json.JSONObject;

import java.nio.channels.NonWritableChannelException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by lenovo on 2018-08-29.
 */

public class RnSuccessActivity extends BaseActivity implements View.OnClickListener {

    private String bank;
    private String name;
    private String logoUrl;
    private String creditcard;
    private String creditcardId;
    private EditText et_repayment;
    private List ratelist = new ArrayList();
    private RateBean rateBean;
    private String feiliu;
    private String channelCode;
    private String type;
    private TextView rnsu_refund;
    private int s;
    private EditText rnsu_variable;
    private String repaymentDay;
    private String billDay;
    private String object;
    private TextView rnsu_reserved;
    private TextView tv_interest;
    private int stroke;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rnsuccess);

        Intent intent = getIntent();
        bank = intent.getStringExtra("bank");
        name = intent.getStringExtra("name");
        logoUrl = intent.getStringExtra("logoUrl");
        creditcard = intent.getStringExtra("creditcard");
        creditcardId = intent.getStringExtra("creditcardId");
        billDay = intent.getStringExtra("billDay");
        repaymentDay = intent.getStringExtra("repaymentDay");
        init_title();
        getData();
        getBill();
    }

    @Override
    public void init_title() {
        super.init_title();
        TextView tv_title = findViewById(R.id.tv_nav_title);
        tv_title.setText(R.string.rnsuccess);
        ImageView iv_bank = findViewById(R.id.iv_nav_back);
        iv_bank.setOnClickListener(this);
        ImageView rnsuccess_logo = findViewById(R.id.rnsuccess_logo);
        TextView rnsuccess_bank = findViewById(R.id.rnsuccess_bank);
        TextView rnsuccess_name = findViewById(R.id.rnsuccess_name);
        TextView rnsuccess_tail = findViewById(R.id.rnsuccess_tail);
        tv_interest = findViewById(R.id.tv_interest);
        rnsu_variable = findViewById(R.id.rnsu_variable);
        final Button rnsu_minus = findViewById(R.id.rnsu_minus);
        final Button rnsu_plus = findViewById(R.id.rnsu_plus);
        et_repayment = findViewById(R.id.et_pepayment);
        TextView tv_submit = findViewById(R.id.tv_submit);
        LinearLayout rnsu_select = findViewById(R.id.rnsu_select);
        rnsu_refund = findViewById(R.id.rnsu_refund);
        rnsu_reserved = findViewById(R.id.rnsu_reserved);
        tv_submit.setOnClickListener(this);
        rnsu_minus.setOnClickListener(this);
        rnsu_plus.setOnClickListener(this);
        rnsu_select.setOnClickListener(this);
        rnsuccess_bank.setText(bank);
        rnsuccess_name.setText(name);
        rnsu_variable.setInputType(InputType.TYPE_NULL);
        rnsuccess_tail.setText(Tailuntils.getCardTailNum(creditcard));
        Glide.with(baseContext).load(BaseHttp.baseImg + logoUrl).into(rnsuccess_logo);
        et_repayment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals("")){

                }else if (feiliu==null){
                    MToast.makeTextShort(RnSuccessActivity.this, "费率类型不匹配，请重新选择").show();
                } else {
                    Float rate = Float.valueOf(feiliu);
                    String a = s.toString();
                    Float imp = Float.valueOf(a);
                    int i = Integer.parseInt(rnsu_variable.getText().toString().trim());
                    double result = rate * imp + i*1.01;
                    Float aFloas = Float.valueOf((float) result);
                    tv_interest.setText(String.valueOf(aFloas));
                    stroke = (int) (imp / 400);
                    if (object==null){
                        MToast.makeTextShort(baseContext,"账单日为空，请重新设置").show();
                        finish();
                    }else {
                        if (stroke > Integer.valueOf(object)) {
                            rnsu_variable.setText(String.valueOf(object));
                        } else {
                            rnsu_variable.setText(String.valueOf(stroke));
                        }

                        Float reserved=imp+aFloas;
                        rnsu_reserved.setText(String.valueOf(reserved));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_nav_back:
                ActivityStack.getScreenManager().popOneActivity(RnSuccessActivity.class);
                break;
            case R.id.tv_submit:
                if (et_repayment.getText().toString().length() == 0) {
                    MToast.makeTextShort(this, "请输入金额！").show();
                } else {
                    submit();
                }
                break;
            case R.id.rnsu_minus:
                int a = Integer.parseInt(rnsu_variable.getText().toString());
                s = a - 1;
                if (s > 0) {
                    rnsu_variable.setText(String.valueOf(s));
                }else if (et_repayment.getText().toString().isEmpty()){
                    MToast.makeTextShort(this, "请先设置还款总金额").show();
                }
                else {
                    MToast.makeTextShort(this, "还款笔数不能为负数").show();
                }
                break;
            case R.id.rnsu_plus:
                if (et_repayment.getText().toString().isEmpty()){
                    MToast.makeTextShort(this, "请先设置还款总金额").show();
                }else if (Integer.valueOf(rnsu_variable.getText().toString())<stroke){
                    int b = Integer.parseInt(rnsu_variable.getText().toString());
                    s = b + 1;
                    rnsu_variable.setText(String.valueOf(s));
                }
                else {
                    MToast.makeTextShort(this, "超过最大还款笔数，请重新设置").show();
                }
                break;
            case R.id.rnsu_select:
                data_dialog();
                break;
        }
    }

    private void data_dialog() {
        ArrayList<String> listdata = new ArrayList<>();
        listdata.add("1");
        listdata.add("2");
        listdata.add("3");
        listdata.add("4");
        listdata.add("5");
        listdata.add("6");
        listdata.add("7");
        listdata.add("8");
        listdata.add("9");
        listdata.add("10");
        listdata.add("11");
        listdata.add("12");
        listdata.add("13");
        listdata.add("14");
        listdata.add("15");
        listdata.add("16");
        listdata.add("17");
        listdata.add("18");
        listdata.add("19");
        listdata.add("20");
        listdata.add("21");
        listdata.add("22");
        listdata.add("23");
        listdata.add("24");
        listdata.add("25");
        listdata.add("26");
        listdata.add("27");
        listdata.add("28");
        listdata.add("29");
        listdata.add("30");
        listdata.add("31");
        PatmentDialog patmentDialog = new PatmentDialog(baseContext, listdata);
        patmentDialog.setTitle("请选择还款日");
        patmentDialog.setOnSelectedListener(new PatmentDialog.OnSelectedListener() {
            @Override
            public void getData(String data) {
                rnsu_refund.setText(data);
            }
        });
        patmentDialog.show();
    }

    public void getData() {
        OkGo.<String>post(BaseHttp.repaymentPlanRate)
                .tag(this)
                .headers("token", PreferencesUtils.getString(this, "token"))
                .params("creditcard", creditcard)
                .params("creditcardId", creditcardId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        rateBean = (RateBean) new DataParse().getBean(response.body(), RateBean.class, 0);
                        if (rateBean.getMsgcode()==100){
                            for (int i = 0; i < rateBean.getData().size(); i++) {
                                ratelist.add(rateBean.getData().get(i).getRate());
                            }
                            if (ratelist.size() == 1) {
                                feiliu = (String) ratelist.get(0);
                            } else {
                                payment_term();
                            }
                        }else if (rateBean.getMsgcode()==601){
                            String msg=rateBean.getMsg();
                            tiedcard_dialog(msg);
                        }else {
                            MToast.makeTextShort(baseContext,rateBean.getMsg());
                        }

                    }
                });



    }

    private void tiedcard_dialog(String msg) {
        BounceTopEnter mBasIn = new BounceTopEnter();
        SlideBottomExit mBasOut = new SlideBottomExit();
        final NormalDialog dialog = new NormalDialog(baseContext);
        dialog.content(msg)
                .style(NormalDialog.STYLE_TWO)
                .titleTextSize(23)
                .showAnim(mBasIn)
                .dismissAnim(mBasOut)
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        finish();
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        Intent intent = new Intent(RnSuccessActivity.this, CreditAddition1Activity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                });
    }

    private void submit() {
        for (int i = 0; i < rateBean.getData().size(); i++) {
            if (feiliu.equals(rateBean.getData().get(i).getRate())) {
                type = rateBean.getData().get(i).getType();
                channelCode = rateBean.getData().get(i).getChannelCode();
            }
        }
        OkGo.<String>post(BaseHttp.addSupport_repaymentplan)
                .tag(this)
                .headers("token", PreferencesUtils.getString(baseContext, "token"))
                .params("creditcardId", creditcardId)
                .params("plat", type)
                .params("channel", channelCode)
                .params("repaymentSum", et_repayment.getText().toString())
                .params("repaymentNum", rnsu_variable.getText().toString())
                .execute(new StringDialogCallback(baseContext) {
                    @Override
                    public void onSuccessResponse(Response<String> response, String msg, String msgCode) {
                        if (msgCode.equals("100")) {
                            try {
                                JSONObject obj = new JSONObject(response.body());
                                JSONObject object = obj.getJSONObject("object");
                                String key = object.getString("key");
                                affirm_dialog(msg, key);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            MToast.makeTextShort(baseContext, msg).show();
                        }
                    }
                });


    }

    private void affirm_dialog(String msg, final String key) {
        BounceTopEnter mBasIn = new BounceTopEnter();
        SlideBottomExit mBasOut = new SlideBottomExit();
        final NormalDialog dialog = new NormalDialog(baseContext);
        dialog.content(msg)
                .style(NormalDialog.STYLE_TWO)
                .titleTextSize(23)
                .showAnim(mBasIn)
                .dismissAnim(mBasOut)
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        submitkey(key);
                    }
                });
    }

    private void submitkey(String key) {
        OkGo.<String>post(BaseHttp.add_repaymentplan)
                .headers("token", PreferencesUtils.getString(baseContext, "token"))
                .params("key", key)
                .execute(new StringDialogCallback(baseContext) {
                    @Override
                    public void onSuccessResponse(Response<String> response, String msg, String msgCode) {
                        if (msgCode.equals("100")) {
                            MToast.makeTextShort(baseContext, msg).show();
                            finish();
                        }
                    }
                });
    }

    private void payment_term() {
        PatmentDialog patmentDialog = new PatmentDialog(RnSuccessActivity.this, (ArrayList<String>) ratelist);
        patmentDialog.setTitle("请选择费率");
        patmentDialog.setOnSelectedListener(new PatmentDialog.OnSelectedListener() {
            @Override
            public void getData(String data) {
                feiliu = data;
            }
        });
        patmentDialog.show();

    }

    public void getBill() {
        OkGo.<String>post(BaseHttp.repaymentStrokeCount)
                .tag(this)
                .headers("token", PreferencesUtils.getString(this, "token"))
                .params("creditcardId", creditcardId)
                .params("billDay", billDay)
                .params("repaymentDay", repaymentDay)
                .params("type", "0")
                .execute(new StringDialogCallback(baseContext) {
                    @Override
                    public void onSuccessResponse(Response<String> response, String msg, String msgCode) {
                        try {
                            JSONObject obj = new JSONObject(response.body());
                            if (obj.getString("msgcode").equals("100")) {
                                    Log.e("执行","2");
                                    object = obj.getString("object");

                            } else {
                                MToast.makeTextShort(RnSuccessActivity.this, obj.getString("msg"));
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }
}
